


var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i) ? true : false;
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i) ? true : false;
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false;
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i) ? true : false;
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());
    }
};
var turn = {
    l0001: "万元",
    l0002: "元",
    l0003: "%",
    l0004: "人",
    l0005: "万吨",
    l0006: "亩",
    l0007: "元/斤",
    l0008: "吨",
    l0009: "公顷",
    l0010: "元/吨",
    l0011: "",
    l0012: "元只"
};


(function() {

    /*
     缓存对象构造函数
     */
    var Cache = function(config) {
        var me = this;
        me._config = config;
        me._render = config ? config.render : d3.select("body").node();
        me._debug = true;
      //  me._server = "http://10.184.85.226:8080/";       //彩鹏机器
        //me._server = "";
     //   me._server = "http://222.128.101.151:28080/";        //服务器
           me._server = "http://192.168.1.4:8080/";     //春朝机器
        //  me._server = "http://122.200.77.134:8080/";
        me._url = me._server + "cmcp/module/getTaskData";
        //me._url = "http://192.168.1.103:8080/cmcp/module/getTaskData";
        //  me._url = "testCache2.json";
    };

    /*
     同步缓存
     */
    if (typeof (Clickmed) === "undefined") {
        Clickmed = {};
    }
    Clickmed.Cache = Cache;
    Cache.prototype.sync = function(isAll, success, error) {
        var me = this, url = me._url, render = me._render;
        var updateTimes = me._updateTimes = [];
        // 加遮罩
        var mark = d3.select(render).append("div").classed("mark", true).html("<div class='num'>0%</div>");
        mark.style("width", "100%").style("height", "100%").style("top", "0px")
                .style("background", "black").style("opacity", "0.7")
                .style("z-index", 9).style("position", "absolute");

        // 加进度条
        var progress = d3.select(render).append("div").classed("progress", true);
        var opts = {
            lines: 18, // The number of lines to draw
            length: 20, // The length of each line
            width: 10, // The line thickness
            radius: 40, // The radius of the inner circle
            corners: 1, // Corner roundness (0..1)
            rotate: 0, // The rotation offset
            direction: 1, // 1: clockwise, -1: counterclockwise
            color: '#FFF', // #rgb or #rrggbb or array of colors
            speed: 1, // Rounds per second
            trail: 60, // Afterglow percentage
            shadow: false, // Whether to render a shadow
            hwaccel: false, // Whether to use hardware acceleration
            className: 'spinner', // The CSS class to assign to the spinner
            zIndex: 11, // The z-index (defaults to 2000000000)
            top: 'auto', // Top position relative to parent in px
            left: 'auto' // Left position relative to parent in px
        };
        // var target = document.getElementById('foo');
        var spinner = new Spinner(opts).spin(progress.node());

        mark.on("click", function() {
            mark.remove();
            progress.remove();
        });
        $.ajax({
            url: url,
            dataType: "json",
            success: function(data) {
                if (typeof data === "string") {
                    data = JSON.parse(data);
                }
                console.log("data--", data);
                for (var i = 0; i < data.length; i++) {
                    data[i]["index"] = data[i]["id"] + "_" + data[i]["time"];
                    updateTimes[data[i]["index"]] = 0;
                }
                if (isAll) {
                    updateAll(data);
                } else {
                    updateNew(data);
                }
            },
            error: function() {
                console.log("error--url", url);
                if (error) {
                    error();
                }
            }
        });

        // 更新全部
        function updateAll(data) {
            me.deleteAll(function() {
                var successNum = 0;

                var successFun = function() {
                    successNum++;
                    if (successNum < data.length) {
                        me.update(data[successNum], successFun, errorFun);
                    }
                    show(successNum / data.length);
                };
                var errorFun = function() {
                    successNum++;
                    if (successNum < data.length) {
                        me.update(data[successNum], successFun, errorFun);
                    }
                    show(successNum / data.length);
                };
                me.update(data[successNum], successFun, errorFun);
            });

        }
        // 更新最新数据
        function updateNew(data) {
            var successNum = 0;

            var successFun = function() {
                successNum++;
                show(successNum / data.length);
            };
            var errorFun = function() {
                successNum++;
                show(successNum / data.length);
            };
            me.listFile(function(list) {
                function allFunction() {
                    successNum++;
                    if (successNum < data.length) {
                        if (list[data[successNum]["index"]] && (list[data[successNum]["index"]]["UPDATETIME"] === data[successNum]["UPDATETIME"])) {
                            allFunction();
                        } else {
                            me.update(data[successNum], allFunction, allFunction);
                        }
                    }
                    show(successNum / data.length);
                }
                if (list[data[0]["index"]] && (list[data[0]["index"]]["UPDATETIME"] === data[0]["UPDATETIME"])) {
                    allFunction();
                } else {
                    me.update(data[0], allFunction, allFunction);
                }
            }, function() {
                updateAll();
            });

        }
        // 展示更新进度
        function show(p) {
            //  console.log("P",p);
            d3.select(".mark .num").html(d3.format(".0f")(p * 100) + "%");

            if (p === 1) {
                mark.remove();
                progress.remove();
                if (success) {
                    success();
                }
            }
        }
    };

    /*
     更新缓存的代码
     */
    Cache.prototype.update = function(keys, success, error) {
        //  var url =URL;
        var me = this, updateTimes = me._updateTimes, debug = me._debug;
        var updateTime = updateTimes[keys["index"]];
        var successFun = function() {
            if (success) {
                success();
                if (debug) {
                    console.log("更新数据成功" + keys["index"]);
                    // alert("更新数据成功"+keys["index"]);
                }

            }
        };
        var errorFun = function() {
            updateTime++;
            updateOnce();
        };

        var updateOnce = function() {
            if (updateTime < 5) {
                if (debug) {
                    console.log("第" + updateTime + "次更新", keys["index"]);
                }

                me.cacheFileFromURL(keys, keys["filepath"], successFun, errorFun);
            } else {
                if (error) {
                    error();
                }
                if (debug) {
                    console.log("更新失败", keys["index"]);
                    // alert("更新失败"+keys["index"]);
                }

            }
        };
        updateOnce();
        // Cache.prototype.cacheFileFromURL(keys, keys["index"], success, error) ;
    };

    /*
     通过URL缓存文件
     keys:
     URL: 文件的URL
     success: 成功以后执行的函数
     error: 执行失败后的函数
     */
    Cache.prototype.cacheFileFromURL = function(keys, URL, success, error) {
        var me = this, server = me._server;

        if (URL) {
            $.ajax({
                timeout: 20000,
                url: server + URL,
                //   dataType:"text",
                success: function(data) {
                    //  console.log("data",data);
                    Cache.prototype.cacheFile(keys, data, function() {
                        window.localStorage[keys["id"] + "_" + keys["time"]] = JSON.stringify(keys);
                        if (success) {
                            success();
                        }
                    }, error);
                    //       console.log("listdata",Data)

                },
                error: function() {
                    //  console.log("获取服务器数据出错，加载本地数据--");
                    if (error) {
                        //  alert(server + URL);
                        error();
                    }
                }
            });
        } else {
            if (error) {
                error();
            }
        }



    };

    /*
     通过字符串缓存文件
     keys:
     object:
     success: 成功以后执行的函数
     error: 执行失败后的函数
     */
    Cache.prototype.cacheFile = function(keys, object, success, error) {
        var me = this, updateTimes = me._updateTimes, debug = me._debug, list = me._list;
        if (isMobile.iOS() || isMobile.Android()) {

            //        return ;
            document.addEventListener("deviceready", onDeviceReady, false);    // device APIs are available


            var t = 5;
            //   onDeviceReady();
            function onDeviceReady() {
                if (typeof (LocalFileSystem) == "undefined") {
                    if (t) {
                        var timer = setTimeout(function() {
                            onDeviceReady();
                            clearTimeout(timer);
                        }, 500);
                    } else {
                        if (error) {
                            error();
                        }
                    }
                }
                window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, gotFSDir, fail);

            }

            function gotFSDir(fileSystem) {
                var Dir = fileSystem.root.getDirectory(keys["id"].toString(), {create: true, exclusive: false}, getFSFile, fail);
            }

            function getFSFile(Dir)
            {
                Dir.getFile(keys["time"].toString(), {create: true, exclusive: false}, gotFileEntry, fail);
            }
            function gotFileEntry(fileEntry) {
                fileEntry.createWriter(gotFileWriter, fail);
            }

            function gotFileWriter(writer) {
                writer.onwriteend = function(evt) {
                    if (debug) {
                        console.log("wriet success,filename" + writer.fileName);
                    }
                    if (success) {
                        success();
                    }

                };
                writer.seek(0);
                writer.write(object);

            }
            ;
            function fail(error) {
                error();
            }
        }
        else {
            success();
        }
    };

    /*
     设置缓存
     keys:
     object:
     success: 成功以后执行的函数
     error: 执行失败后的函数
     */
    Cache.prototype.set = function(keys, object, success, error) {

    };

    Cache.prototype.deleteAll = function(callback) {
        var me = this, storage = window.localStorage;
        me.listFile(function(list) {
            var deleteNum = 0;
            var temp = 0;
            for (var it in list) {
                temp++;
            }
            if (!temp) {
                if (callback) {
                    callback();
                    return;
                }
            }
            for (var ii in list) {
                (function() {
                    var i = ii;
                    me.deleteOne({id: list[i]["id"], time: list[i]["time"]}, function() {
                        console.log("-s-", list[i]["id"] + "_" + list[i]["time"]);
                        storage.removeItem(list[i]["id"] + "_" + list[i]["time"]);
                        deleteCallback();
                    }, function() {
                        console.log("-f-", list[i]["id"] + "_" + list[i]["time"]);
                        storage.removeItem(list[i]["id"] + "_" + list[i]["time"]);
                        deleteCallback();
                    });
                })();
            }
            function deleteCallback() {
                deleteNum++;
                console.log("el", deleteNum, temp)
                if (deleteNum === temp) {
                    if (callback) {
                        callback();
                    }
                }
            }
        });
    };
    /*
     删除缓存
     keys:
     success:
     error:
     */
    Cache.prototype.deleteOne = function(keys, success, error) {
        console.log("del", keys);
        var me = this, storage = window.localStorage;
        if (isMobile.iOS() || isMobile.Android()) {

            document.addEventListener("deviceready", onDeviceReady, false);
            var t = 5;
            //  onDeviceReady();
            function onDeviceReady() {
                if (typeof (LocalFileSystem) == "undefined") {
                    if (t) {
                        var timer = setTimeout(function() {
                            onDeviceReady();
                            clearTimeout(timer);
                        }, 500);
                    } else {
                        if (error) {
                            error();
                        }
                    }
                }
                window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, gotFSDir, fail);

            }
            function gotFSDir(fileSystem) {
                console.log('keys', keys);
                var Dir = fileSystem.root.getDirectory(keys["id"].toString(), null, getFSFile, fail);
            }

            function getFSFile(Dir)
            {
                Dir.getFile(keys["time"].toString(), null, gotFileEntry, fail);
            }

            function gotFileEntry(fileEntry) {
                fileEntry.remove(suc, fail);
            }
            function fail(e) {
                if (error) {
                    error();
                }
            }
            function suc(entry) {
                if (success) {
                    success();
                }
            }

        }
    };


    /*
     读取缓存
     keys:
     success:
     error:
     */
    Cache.prototype.get = function(keys, success, error) {

    };

    /*
     读取缓存
     keys:
     success:
     error:
     flag:
     */
    Cache.prototype.read = function(keys, success, error) {
        if (isMobile.iOS() || isMobile.Android()) {
            //    alert("ios");
//                alert("DeviceReady ==",DeviceReady)

            document.addEventListener("deviceready", onDeviceReady, false);
            var t = 5;
            //   onDeviceReady();
            function onDeviceReady() {
                t--;
                if (typeof (LocalFileSystem) == "undefined") {
                    if (t) {
                        var timer = setTimeout(function() {
                            onDeviceReady();
                            clearTimeout(timer);
                        }, 500);
                    } else {
                        if (error) {
                            error();
                        }
                    }
                } else {
                    window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, gotFSDir, fail);
                }


            }

            function gotFSDir(fileSystem) {
                var Dir = fileSystem.root.getDirectory(keys["id"].toString(), null, getDirFile, fail);
            }

            function getDirFile(Dir)
            {
                Dir.getFile(keys["time"].toString(), null, gotFileEntry, fail);
            }


            function gotFileEntry(fileEntry) {

                fileEntry.file(gotFile, fail);

            }


            function gotFile(file) {
                readAsText(file);
            }

            function readAsText(file) {
                var reader = new FileReader();
                reader.onloadend = function(evt) {
                    console.log("read success,evt", evt);


                    success(evt.target._result);


                };
                reader.readAsText(file);

            }
            function fail() {
                console.log("读取系统数据失败");
                if (error) {
                    error("读取系统数据失败");
                }

            }

        }
        else {
            Cache.prototype.cacheFileFromURL(keys, URL, success, error);

        }
    };

    Cache.prototype.listFile = function(success, error) {
        var me = this, url = me._url, list = {};
        var storage = window.localStorage;
        for (var i = 0; i < storage.length; i++) {
            //key(i)获得相应的键，再用getItem()方法获得对应的值
            try {
                var keyi = JSON.parse(storage.getItem(storage.key(i)));
                if (keyi["id"] && keyi["time"]) {
                    list[storage.key(i)] = keyi;
                }
            } catch (e) {

            }

        }
        if (success) {
            success(list);
        }
    };

    Cache.prototype.listTimeById = function(id, success, error) {
        var me = this;
        var times = [];
        me.listFile(function(list) {
            for (var i in list) {
                if (list[i]["id"] == id)
                    times.push(list[i].time);
            }
            if (times.length) {
                if (success) {
                    success(times);
                }
            } else {
                if (error) {
                    error();
                }
            }


        });
    };


})();